﻿using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Model.ReportFilter;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace LM.CB.K3Cloud.Plugin
{
    /// <summary>
    /// 获取存货收发存数据
    /// </summary>
    /// <remarks>
    /// 功能：1.获取选中日期存货收发存汇报表数据
    /// 创建人：lxl
    /// 创建日期：2024-04-9
    /// </remarks>
    [Description("获取收发存汇总表")]
    [Kingdee.BOS.Util.HotUpdate]
    public class GetInstockProductBillPlugin : AbstractBillPlugIn
    {
        // private string[] TEMP_TABLE_NAME_LIST; //创建临时表使用
        private readonly IDBService DBSERVICE = ServiceHelper.GetService<IDBService>();
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            switch (e.BarItemKey.ToUpperInvariant())
            {
                //case "SAVE": 表单定义的事件都可以在这里执行，需要通过事件的代码[大写]区分不同事件
                //break;
                case "RDLV_GETDATA"://点击获取存货数据按钮

                    StringBuilder sbBuilder = new StringBuilder();
                    DynamicObject ORG = this.View.Model.DataObject["F_RDLV_ORGID"] as DynamicObject;
                    string forgId = "";//组织内码
                    string forgNumber = "";//组织编码
                    if (ORG != null)
                    {
                        forgId = ORG["ID"].ToString(); // 组织内码
                        forgNumber = ORG["Number"].ToString(); // 组织编码
                    }
                    else
                    {
                        this.View.ShowMessage("请选择组织后再进行查询");
                        return;
                    }
                    string YEAR = Convert.ToString(this.View.Model.GetValue("F_RDLV_YEAR"));//年度
                    string MONTH = Convert.ToString(this.View.Model.GetValue("F_RDLV_MONTH"));//期间                      
                    if (YEAR == "" || MONTH == "")
                    {
                        this.View.ShowMessage("请选择年度和期间后再进行查询");
                        return;
                    }
                    //获取数据
                    DataTable dt = GetSql(forgId, forgNumber, YEAR, MONTH);
                    // 填充数据到界面
                    SetData(dt);
                    //DropTempTable();
                    // 下达一个指令
                    //this.View.SendDynamicFormAction(this.View);
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 从系统标准报表“存货收发存汇总表中获取数据”
        /// </summary>
        /// <param name="forgId"></param>
        /// <param name="forgNumber"></param>
        /// <param name="YEAR"></param>
        /// <param name="MONTH"></param>
        /// <returns></returns>
        private DataTable GetSql(string forgId, string forgNumber, string YEAR, string MONTH)
        {
            #region 抓取收发存汇总表中的数据
            /*从成本计算单报表中读取数据*/

            ISysReportService sysReporSservice = ServiceFactory.GetSysReportService(this.Context);
            IPermissionService permissionService = ServiceFactory.GetPermissionService(this.Context);

            /*创建DataTable,用于获取从报表取出的数据*/
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("FMATERIALBASEID", typeof(Int32));//记录物料内码
            dtResult.Columns.Add("FMATERIALID", typeof(string));//记录物料编码
            dtResult.Columns.Add("FUnitID", typeof(string));//单位内码
            dtResult.Columns.Add("FSTOCKID", typeof(string));//仓库内码
            dtResult.Columns.Add("FINITQTY", typeof(string));//期初结存-数量
            dtResult.Columns.Add("FINITPRICE", typeof(string));//期初结存-单价
            dtResult.Columns.Add("FINITAMOUNT", typeof(double));//期初结存-金额
            dtResult.Columns.Add("FRECEIVEQTY", typeof(double)); //本期收入-数量
            dtResult.Columns.Add("FRECEIVEPRICE", typeof(string));//本期收入-单价
            dtResult.Columns.Add("FRECEIVEAMOUNT", typeof(string));//本期收入-金额
            dtResult.Columns.Add("FSENDQTY", typeof(double)); //本期发出-数量
            dtResult.Columns.Add("FSENDPRICE", typeof(string));//本期发出-单价
            dtResult.Columns.Add("FSENDAMOUNT", typeof(string));//本期发出-金额
            dtResult.Columns.Add("FENDQTY", typeof(string));//期末结存-数量
            dtResult.Columns.Add("FENDPRICE", typeof(string));//期末结存-单价
            dtResult.Columns.Add("FENDAMOUNT", typeof(string)); //期末结存-金额


            //加载字段比较元数据
            var filterMetadata = FormMetaDataCache.GetCachedFilterMetaData(this.Context);
            //报表元数据。
            var reportMetadata = FormMetaDataCache.GetCachedFormMetaData(this.Context, "HS_INOUTSTOCKSUMMARYRPT"); //收发存汇总表标识
                                                                                                                   //加载过滤条件元数据
            var reportFilterMetadata = FormMetaDataCache.GetCachedFormMetaData(this.Context, "HS_INOUTSTOCKSUMMARYFILTER");///收发存汇总表过滤条件标识
            var reportFilterServiceProvider = reportFilterMetadata.BusinessInfo.GetForm().GetFormServiceProvider();
            //创建报表过滤模型
            var model = new SysReportFilterModel();
            model.SetContext(this.Context, reportFilterMetadata.BusinessInfo, reportFilterServiceProvider);
            model.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
            model.FilterObject.FilterMetaData = filterMetadata;
            model.InitFieldList(reportMetadata, reportFilterMetadata);
            model.GetSchemeList();

            //获取过滤方案，可以通过LoadScheme("Id")，查询报表默认存在的一些过滤方案
            //SELECT * FROM T_BAS_FILTERSCHEME where fschemename=""
            //遍历所有的方案*每个组织都有一个方案，所以*
            string fschemeid = "66495167b3a3d3"; //过滤方案的ID
            var entity = model.Load(fschemeid);

            var filters = model.GetFilterParameter();
            DynamicObject orgObj = LoadBDObject("ORG_Organizations", forgNumber);//构建数据包
            filters.CustomFilter["ACCTGORGID"] = orgObj;
            filters.CustomFilter["ACCTGORGID_id"] = forgId;
            filters.CustomFilter["Year"] = YEAR;       //开始会计年度
            filters.CustomFilter["EndYear"] = YEAR;     //结束会计年度:取系统当前年份
            filters.CustomFilter["Period"] = MONTH;    //开始会计期间
            filters.CustomFilter["EndPeriod"] = MONTH;  //结束会计期间:取系统当前月份
                                                        //报表参数
            IRptParams p = new RptParams();
            p.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
            p.StartRow = 1; // StartRow和EndRow是报表数据分页的起始行数和截至行数，一般取所有数据，所以EndRow取int最大值
            p.EndRow = int.MaxValue;
            p.FilterParameter = filters;
            p.FilterFieldInfo = model.FilterFieldInfo;
            p.BaseDataTempTable.AddRange(permissionService.GetBaseDataTempTable(this.Context, reportMetadata.BusinessInfo.GetForm().Id));

            using (DataTable dt = sysReporSservice.GetData(this.Context, reportMetadata.BusinessInfo, p))
            {
                foreach (DataRow item in dt.Rows) //循环结果集
                {

                    if (item["FMATERIALID"].ToString().Contains("总计") == false)
                    {
                        DataRow drw = dtResult.NewRow();
                        drw["FMATERIALBASEID"] = item["FMATERIALBASEID"];//物料内码
                        drw["FMATERIALID"] = item["FMATERIALID"]; //物料编码
                        drw["FUnitID"] = item["FUnitID"];//单位内码
                        drw["FSTOCKID"] = item["FSTOCKID"];//仓库内码
                        drw["FINITQTY"] = item["FINITQTY"];//期初结存-数量
                        drw["FINITPRICE"] = item["FINITPRICE"];//期初结存-单价
                        drw["FINITAMOUNT"] = item["FINITAMOUNT"];//期初结存-金额
                        drw["FRECEIVEQTY"] = item["FRECEIVEQTY"];//本期收入-数量
                        drw["FRECEIVEPRICE"] = item["FRECEIVEPRICE"];//本期收入-单价
                        drw["FRECEIVEAMOUNT"] = item["FRECEIVEAMOUNT"];//本期收入-金额
                        drw["FSENDQTY"] = item["FSENDQTY"];//本期发生-数量
                        drw["FSENDPRICE"] = item["FSENDPRICE"];//本期发生-单价
                        drw["FSENDAMOUNT"] = item["FSENDAMOUNT"];//本期发生-金额
                        drw["FENDQTY"] = item["FENDQTY"];//期末结存-数量
                        drw["FENDPRICE"] = item["FENDPRICE"];//期末结存-单价
                        drw["FENDAMOUNT"] = item["FENDAMOUNT"];//期末结存-金额
                        dtResult.Rows.Add(drw);
                    }

                }
            }

            ServiceFactory.CloseService(sysReporSservice);
            ServiceFactory.CloseService(permissionService);

            //将数据存到数据表临时表中

            //string connectionString = "Data Source=.;database=AIS20231208101656;Uid=sa;Pwd=123qwe!@#;";
            //SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            //sqlbulkcopy.DestinationTableName = tempTableName;//数据库中的自己创建表名
            //sqlbulkcopy.WriteToServer(dtResult);
            #endregion

            //string strsql = "select * from " + tempTableName;
            DataTable dt1 = dtResult;
            return dt1;

        }
        /// 构造基础资料
        /// </summary>
        /// <param name="myFilter"></param>
        private DynamicObject LoadBDObject(string formId, string number)
        {
            FormMetadata meta = MetaDataServiceHelper.Load(this.Context, formId) as FormMetadata;
            // 构建查询参数，设置过滤条件    
            QueryBuilderParemeter queryParam = new QueryBuilderParemeter();
            queryParam.FormId = formId;
            queryParam.BusinessInfo = meta.BusinessInfo;
            queryParam.FilterClauseWihtKey = string.Format(" {0} = '{1}' ", meta.BusinessInfo.GetForm().NumberFieldKey, number);
            var bdObjs = BusinessDataServiceHelper.Load(this.Context, meta.BusinessInfo.GetDynamicObjectType(), queryParam);
            return bdObjs[0];
        }

        /// 为单据体创建一行数据
        ///
        private void SetData(DataTable dt)
        {
            this.View.Model.DeleteEntryData("FEntity");
            //this.View.Model.CreateNewData
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                this.View.Model.CreateNewEntryRow("FEntity");
                int entryCurrentRowIndex = this.Model.GetEntryRowCount("FEntity") - 1;
                this.View.Model.SetItemValueByNumber("F_RDLV_WLBM", Convert.ToString(dt.Rows[i]["FMATERIALID"]), entryCurrentRowIndex);//物料编码
                this.View.Model.SetItemValueByID("F_RDLV_JBDW", Convert.ToString(dt.Rows[i]["FUnitID"]), entryCurrentRowIndex);//基本单位
                this.View.Model.SetItemValueByID("F_RDLV_CK", Convert.ToString(dt.Rows[i]["FSTOCKID"]), entryCurrentRowIndex);//仓库
                this.View.Model.SetValue("F_RDLV_QCJCSL", dt.Rows[i]["FINITQTY"].ToString(), entryCurrentRowIndex);//分母
                this.View.Model.SetValue("F_RDLV_QCJCDJ", dt.Rows[i]["FINITPRICE"].ToString(), entryCurrentRowIndex); //是否跳层
                this.View.Model.SetValue("F_RDLV_QCJCJE", dt.Rows[i]["FINITAMOUNT"].ToString(), entryCurrentRowIndex); //直接材料&标准数量
                this.View.Model.SetValue("F_RDLV_BQSRSL", dt.Rows[i]["FRECEIVEQTY"].ToString(), entryCurrentRowIndex); //直接材料&标准单价
                this.View.Model.SetValue("F_RDLV_BQSRDJ", dt.Rows[i]["FRECEIVEPRICE"].ToString(), entryCurrentRowIndex); //直接材料&标准金额
                this.View.Model.SetValue("F_RDLV_BQSRJE", dt.Rows[i]["FRECEIVEAMOUNT"].ToString(), entryCurrentRowIndex); //直接材料&实际数量
                this.View.Model.SetValue("F_RDLV_BQFCSL", dt.Rows[i]["FSENDQTY"].ToString(), entryCurrentRowIndex); //直接材料&实际单价
                this.View.Model.SetValue("F_RDLV_BQFCDJ", dt.Rows[i]["FSENDPRICE"].ToString(), entryCurrentRowIndex); //直接材料&实际金额
                this.View.Model.SetValue("F_RDLV_BQFCJE", dt.Rows[i]["FSENDAMOUNT"].ToString(), entryCurrentRowIndex); //直接人工&标准人工
                this.View.Model.SetValue("F_RDLV_QMJCSL", dt.Rows[i]["FENDQTY"].ToString(), entryCurrentRowIndex); //直接人工&实际人工
                this.View.Model.SetValue("F_RDLV_QMJCDJ", dt.Rows[i]["FENDPRICE"].ToString(), entryCurrentRowIndex); //制造费用&标准制造费用
                this.View.Model.SetValue("F_RDLV_QMJCJE", dt.Rows[i]["FENDAMOUNT"].ToString(), entryCurrentRowIndex); //制造费用&实际制造费用
            }
            this.View.UpdateView("FEntity");
        }
        private DataTable GetNewDataTable(DataTable dt, string condition)
        {
            DataTable newdt = new DataTable();
            newdt = dt.Clone();
            DataRow[] dr = dt.Select(condition);
            for (int i = 0; i < dr.Length; i++)
            {
                newdt.ImportRow((DataRow)dr[i]);
            }
            return newdt;//返回的查询结果
        }
        #region 删除临时表
        //public void DropTempTable()
        //{
        //    if (TEMP_TABLE_NAME_LIST != null)
        //    {
        //        foreach (string tempTableNameItem in TEMP_TABLE_NAME_LIST)
        //        {
        //            string statement = string.Format("/*dialect*/DROP TABLE {0};", tempTableNameItem);
        //            DBUtils.Execute(this.Context, statement.ToString());
        //        }

        //    }

        //}
        #endregion
    }
}
